package com.task.scheduling.util;

import org.apache.commons.lang.StringUtils;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: facade-console
 * @description:
 * @author: zhouliangliang
 * @create: 2019-03-14 19:25
 **/
public class HttpClientUtil {

    private static Logger log = LoggerFactory.getLogger(HttpClientUtil.class);
    private static CloseableHttpClient client = HttpClients.createDefault();

    private static RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(3000)
            .setConnectionRequestTimeout(1000).setSocketTimeout(5000).build();


    /**
     * 发送Get请求
     *
     * @param url
     *            请求的地址
     * @param headers
     *            请求的头部信息
     * @param params
     *            请求的参数
     * @param encoding
     *            字符编码
     */
    public static String sendGet(String url, Map<String, String> headers, Map<String, String> params, String encoding) {
        HttpGet httpGet = null;
        try {
            url = url + (null == params ? "" : assemblyParameter(params));
            httpGet = new HttpGet(url);
            httpGet.setConfig(requestConfig);

            if (null != headers)
                httpGet.setHeaders(assemblyHeader(headers));
            HttpResponse response = client.execute(httpGet);

            HttpEntity entity = response.getEntity();
            return EntityUtils.toString(entity, StringUtils.isEmpty(encoding) ? "utf-8" : encoding);
        } catch (Exception e) {
            log.error("HttpClientUtil.sendGet error" + e.getMessage(), e);
            return null;
        } finally {
            httpGet.releaseConnection();
        }
    }

    /**
     * 发送Post请求
     *
     * @param url
     *            请求的地址
     * @param headers
     *            请求的头部信息
     * @param params
     *            请求的参数
     * @param encoding
     *            字符编码
     * @return
     * @throws ClientProtocolException
     * @throws IOException
     */
    public static String sendPost(String url, Map<String, String> headers, Map<String, String> params, String encoding) {
        HttpPost post = null;
        try {
            post = new HttpPost(url);
            post.setConfig(requestConfig);
            List<NameValuePair> list = new ArrayList<NameValuePair>();
            for (String temp : params.keySet()) {
                list.add(new BasicNameValuePair(temp, params.get(temp)));
            }
            post.setEntity(new UrlEncodedFormEntity(list, encoding));

            if (null != headers)
                post.setHeaders(assemblyHeader(headers));
            HttpResponse response = client.execute(post);
            HttpEntity entity = response.getEntity();
            return EntityUtils.toString(entity, StringUtils.isEmpty(encoding) ? "utf-8" : encoding);
        } catch (Exception e) {
            log.error("HttpClientUtil.sendPost error" + e.getMessage(), e);
            return null;
        } finally {
            post.releaseConnection();
        }
    }

    /**
     * 组装头部信息
     *
     * @param headers
     * @return
     */
    public static Header[] assemblyHeader(Map<String, String> headers) {
        Header[] allHeader = new BasicHeader[headers.size()];
        int i = 0;
        for (String str : headers.keySet()) {
            allHeader[i] = new BasicHeader(str, headers.get(str));
            i++;
        }
        return allHeader;
    }

    /**
     * 组装请求参数
     *
     * @param parameters
     * @return
     */
    public static String assemblyParameter(Map<String, String> parameters) {
        String para = "?";
        for (String str : parameters.keySet()) {
            para += str + "=" + parameters.get(str) + "&";
        }
        return para.substring(0, para.length() - 1);
    }

    // TODO demo
    public static void main(String[] args) {
        Map<String, String> param = new HashMap<String, String>();
        try {
           String str = HttpClientUtil.sendGet("http://www.baidu.com", param, param, "utf-8");
            System.out.println(str);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
